﻿using blackhouse.BlackApart.Business.Opinions;
using blackhouse.mojoPortalExtend;
using blackhouse.mojoPortalExtend.Urls;
using blackhouse.WebNemo.Business.Groups;
using mojoPortal.Business;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace blackhouse.StareKino.Web.Navigation {
    public class OpinionUrlSupport : UrlSupport {

        #region Fields

        private int urlVariantIdx = 0;

        private IOpinion opinion;
        private GroupRecord record;

        #endregion

        #region Constructors

        public OpinionUrlSupport(GroupRecord opinionRecord, IOpinion opinion) {
            this.opinion = opinion;
            this.record = opinionRecord;
            this.OldUrl = String.Empty;
            this.NewUrl = this.GetNewUrl(this.urlVariantIdx);
            this.Guid = Guid.NewGuid();
            string realUrl = "~/OpinionDetails.aspx?opinion=" + this.opinion.Id;
            PageProvider page = new PageProvider();
            PageSettings opinionsPage = page.FindCmsPageByFunctionality("opinions");
            if (opinionsPage != null)
                realUrl = realUrl + "&pageId=" + opinionsPage.PageId;
            this.RealUrl = realUrl;
        }

        #endregion

        #region Methods

        private string GetNewUrl(int variantIdx) {
            StringBuilder buildUrl = new StringBuilder();
            buildUrl.Append(this.opinion.Publisher.FirstName);
            buildUrl.Append("-");
            buildUrl.Append(this.opinion.Publisher.LastName);
            buildUrl.Append("-");
            buildUrl.AppendFormat("{0:D}", this.opinion.PublishedDate);
            buildUrl.Append("-");
            buildUrl.Append(this.opinion.GetAssociatedApartmentGroup().ShortName);

            string url = buildUrl.ToString().RemovePolishChars().CleanStringForUrl();
            switch (variantIdx) {
                case 0:
                    return "~/" + url;
                case 1:
                    return "~/" + url + "-i-" + opinion.Id;
                default:
                    throw new UrlInUseException(this);
            }
        }

        public override void ChangeToOtherNewUrl() {
            if (this.NewUrl.Equals(GetNewUrl(this.urlVariantIdx), StringComparison.InvariantCultureIgnoreCase))
                this.urlVariantIdx++;
            this.NewUrl = GetNewUrl(this.urlVariantIdx);
        }

        public override void Save() {
            this.record.SetValue("url", this.NewUrl);
            this.record.Save();
        }

        #endregion

    }
}